﻿using Crm.Infrastructure.IOC;
using Crm.Service.Instance;
using CRM.Infrastructure.Attr;
using CRM.Infrastructure.Dto.Response.Dictionary;
using CRM.Infrastructure.Dto.Response;
using CRM.Infrastructure.IOC;
using CRM.Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using CRM.Service.EFCore;
using CRM.Infrastructure.Dto.Response.Customer;
using CRM.Infrastructure.Dto.Response.Vip;
using CRM.Infrastructure.Dto.Request.Customer;
using CRM.Infrastructure.EFCore.Mysql;
using CRM.Infrastructure.Tools;

namespace CRM.Service.Instance
{
    [Inject_]
    public class CustomerVip_Service : Base_Service, I_CustomerVip_Service
    {
        private readonly Customer_IOC _customer_IOC;
        private readonly Dictionary_IOC _dictionary_IOC;
        private readonly Login_IOC _login_IOC;

        public CustomerVip_Service(Customer_IOC customer_IOC, Dictionary_IOC dictionary_IOC, Login_IOC login_IOC)
        {
            _customer_IOC = customer_IOC;
            _dictionary_IOC = dictionary_IOC;
            _login_IOC = login_IOC;
        }

        public async Task<Api_Response_Dto> Get_Level()
        {
            var now = DateTime.Now;
            var iq = _dictionary_IOC._sys_Dictionary_EFCore.QueryAll(d => d.DDtId == "6e78ff75ecf811ef9301902e1656e0d2");
            var data = await iq.Select(d => new Dictionary_Type_Response_Dto
            {
                id = d.DId,
                name = d.DName,
                explain=d.DExplain,
                discount=d.DDiscount,
                count=0
            }).ToListAsync();
            data.ForEach(d =>
            {
                var iq2 = _customer_IOC._customer_vip_EFCore.QueryAll(e => e.CvLevel == d.id);
                foreach(var i in iq2)
                {
                    d.count++;
                }
            });
            

            return Result(1, "ok", new
            {
                data
            });
        }
        public async Task<Api_Response_Dto> Vip_Consumption(string uid)
        {
            var now = DateTime.Now;
            var vip = _customer_IOC._customer_vip_EFCore.QueryAll(d => d.CvResponsible == uid);

            // 获取所有相关的订单
            var iq = _customer_IOC._order_EFCore.QueryAll(d => vip.Select(e => e.CvId).Contains(d.OCvipId) && d.OPayment==1).OrderBy(d => d.ODateTime);
            var data = await iq.Select(d => new Customer_Vip_Response_Dto
            {
                id = d.OId,
                time = d.ODateTime!.Value.ToString("MM"),
                money = d.OMoney,
                payment = 0
            }).ToListAsync();

            // 初始化每月的总金额字典
            var monthlyGrowthDict = new Dictionary<int, decimal?>();

            // 累计每个月的金额
            foreach (var order in data)
            {
                int month = int.Parse(order.time); // 将月份转换为整数（1-12）

                if (!monthlyGrowthDict.ContainsKey(month))
                {
                    monthlyGrowthDict[month] = 0;
                }

                monthlyGrowthDict[month] += order.money;

                // 设置 payment 字段
                order.payment = month;
            }

            // 构建最终返回的数据结构
            var resultData = new
            {
                monthlyGrowth = monthlyGrowthDict.ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value),
                revenueBreakdown = new Dictionary<string, decimal>
        {
            { "recharge", 60 }, // 示例数据
            { "consume", 35 },
            { "gift", 5 }
        }
            };

            return Result(1, "ok", resultData);
        }
        

        public async Task<Api_Response_Dto> Get_vip()
        {
            var iq = _customer_IOC._customer_vip_EFCore.QueryAll();
            
            var data = await iq.Select(d => new Customer_Vip_Response_Dto
            {
                id = d.CvId,
                name = d.CvName,
                address = d.CvAddress,
                career = d.CvCareer,
                consumptionAmount = d.CvConsumptionAmount,
                consumptionGiftAmount=d.CvConsumptionGiftAmount,
                createTime = d.CvCreateTime,
                CustomerId = d.CvCustomerId,
                Desc = d.CvDesc,
                giftAmount = d.CvGiftAmount,
                LastTime = d.CvLastTime,
                phone = d.CvPhone,
                qq=d.CvQq,
                rechargeAmount = d.CvRechargeAmount.ToString(),
                Responsible = d.CvResponsible,
                transactionCount = d.CvTransactionCount,
                wechat=d.CvWechat,
                lv=d.CvLevel
            }).ToListAsync();
            var Responsible = await _login_IOC._sys_User_EFCore.QueryAll(d=>data.Select(e=>e.Responsible).Contains(d.UId)).ToListAsync();
            var CustomerId = await _customer_IOC._customer_EFCore.QueryAll(d => data.Select(e => e.CustomerId).Contains(d.CId)).ToListAsync();
            var lv = await _dictionary_IOC._sys_Dictionary_EFCore.QueryAll(d => data.Select(e => e.lv).Contains(d.DId)).ToListAsync();
            var resultDate = new Dictionary<string, decimal?>();
            data.ForEach(d =>
            {
                d.Responsible = Responsible.Where(e => e.UId == d.Responsible).SingleOrDefault()?.UName!;
                d.CustomerId = CustomerId.Where(e => e.CId == d.CustomerId).SingleOrDefault()?.CName!;
                d.lv = lv.Where(e => e.DId == d.lv).SingleOrDefault()?.DName!;

                resultDate.Add(d.name, d.consumptionAmount);
            });
            

            return Result(1, "ok", new
            {
                data,
                resultDate
            });
        }
        public async Task<Api_Response_Dto> Get_vip_Order(string? id)
        {
            if (id==null)
            {
                var iq = _customer_IOC._order_EFCore.QueryAll();
                var data = await iq.Select(d => new Customer_Vip_Response_Dto
                {
                    id = d.OId,
                    money = d.OMoney,
                    payment = d.OPayment,
                    createTime = d.ODateTime
                }).ToListAsync();
                var Responsible = await _login_IOC._sys_User_EFCore.QueryAll(d => data.Select(e => e.Responsible).Contains(d.UId)).ToListAsync();
                var CustomerId = await _customer_IOC._customer_EFCore.QueryAll(d => data.Select(e => e.CustomerId).Contains(d.CId)).ToListAsync();
                
                data.ForEach(d =>
                {
                    decimal? money = 0;
                    var iq2 = _customer_IOC._order_Product_EFCore.QueryAll(e => e.OId == d.id);
                    d.Responsible = Responsible.Where(e => e.UId == d.Responsible).SingleOrDefault()?.UName!;
                    d.CustomerId = CustomerId.Where(e => e.CId == d.CustomerId).SingleOrDefault()?.CName!;
                    var data2 = iq2.Select(d => new Customer_Vip_Response_Dto
                    {
                        id = d.OId,
                        money = d.OpMoney,

                    }).ToList();

                    data2.ForEach(e =>
                    {
                        money += e.money;
                        d.money = money;
                    });
                });

                return Result(1, "ok", new
                {
                    data
                });
            }
            else
            {
                var iq = _customer_IOC._order_EFCore.QueryAll(d => d.OCvipId == id);
                var data = await iq.Select(d => new Customer_Vip_Response_Dto
                {
                    id = d.OId,
                    money = d.OMoney,
                    payment = d.OPayment,
                    createTime = d.ODateTime
                }).ToListAsync();
                var Responsible = await _login_IOC._sys_User_EFCore.QueryAll(d => data.Select(e => e.Responsible).Contains(d.UId)).ToListAsync();
                var CustomerId = await _customer_IOC._customer_EFCore.QueryAll(d => data.Select(e => e.CustomerId).Contains(d.CId)).ToListAsync();

                data.ForEach(d =>
                {
                    decimal? money = 0;
                    var iq2 = _customer_IOC._order_Product_EFCore.QueryAll(e => e.OId == d.id);
                    d.Responsible = Responsible.Where(e => e.UId == d.Responsible).SingleOrDefault()?.UName!;
                    d.CustomerId = CustomerId.Where(e => e.CId == d.CustomerId).SingleOrDefault()?.CName!;
                    var data2 = iq2.Select(d => new Customer_Vip_Response_Dto
                    {
                        id = d.OId,
                        money = d.OpMoney,

                    }).ToList();

                    data2.ForEach(e =>
                    {
                        money += e.money;
                        d.money = money;
                    });
                });

                return Result(1, "ok", new
                {
                    data
                });
            }
           
        }
        
        public async Task<Api_Response_Dto> Get_vip_single(string id)
        {
            var iq = _customer_IOC._customer_vip_EFCore.QueryAll(d => d.CvId == id);
            var iq2 = _customer_IOC._recharge_EFCore.QueryAll(d => d.RCvipId == id);
            var data = await iq.Select(d => new Customer_Vip_Response_Dto
            {
                id = d.CvId,
                name = d.CvName,
                address = d.CvAddress,
                career = d.CvCareer,
                consumptionAmount = d.CvConsumptionAmount,
                consumptionGiftAmount = d.CvConsumptionGiftAmount,
                createTime = d.CvCreateTime,
                CustomerId = d.CvCustomerId,
                Desc = d.CvDesc,
                giftAmount = d.CvGiftAmount,
                LastTime = d.CvLastTime,
                phone = d.CvPhone,
                qq = d.CvQq,
                rechargeAmount = d.CvRechargeAmount.ToString(),
                Responsible = d.CvResponsible,
                transactionCount = d.CvTransactionCount,
                wechat = d.CvWechat,
                balance=d.CvBalance,
                lv=d.CvLevel,
            }).ToListAsync();
            var lv = await _dictionary_IOC._sys_Dictionary_EFCore.QueryAll(d => data.Select(e => e.lv).Contains(d.DId)).ToListAsync();
            var data2 = await iq2.Select(d => new Customer_Vip_Response_Dto
            {
                id = d.RId,
                rechargeAmount=d.RMoney.ToString(),
                createTime=d.RDateTime,
            }).ToListAsync();
            var Responsible = await _login_IOC._sys_User_EFCore.QueryAll(d => data.Select(e => e.Responsible).Contains(d.UId)).ToListAsync();
            var CustomerId = await _customer_IOC._customer_EFCore.QueryAll(d => data.Select(e => e.CustomerId).Contains(d.CId)).ToListAsync();
            data.ForEach(d =>
            {
                d.Responsible = Responsible.Where(e => e.UId == d.Responsible).SingleOrDefault()?.UName!;
                d.CustomerId = CustomerId.Where(e => e.CId == d.CustomerId).SingleOrDefault()?.CName!;
                d.lv = lv.Where(e => e.DId == d.lv).SingleOrDefault()?.DName!;
                if (data2.Count == 0)
                {
                    d.rechargeAmount = "0";
                }
   
               
            });

            return Result(1, "ok", new
            {
                data,
                data2
            });
        }
        
        public async Task<Api_Response_Dto> Get_vip_Tolist()
        {
            var iq = _customer_IOC._customer_vip_EFCore.QueryAll();

            var data = await iq.Select(d => new Customer_Vip_Response_Dto
            {
                rechargeAmount = d.CvRechargeAmount.ToString(),
                count = 0,
                creationTime = d.CvCreationTime,
                addmonth = 0,
                money=0,
            }).ToListAsync();
            data.ForEach(d =>
            {
                d.count = data.Count;
                foreach (var i in data)
                {
                    if (i.creationTime > DateTime.Now.AddDays(1 - DateTime.Now.Day) && i.creationTime < DateTime.Now.AddDays(1 - DateTime.Now.Day).AddMonths(1))
                    {
                        d.addmonth += 1;
                    }
                    d.money +=Convert.ToDecimal(i.rechargeAmount);
                }
                
            });
            
            return Result(1, "ok", new
            {
                data
            });
        }
        
        public async Task<Api_Response_Dto> update_vip(Dictionary_Vip_Response_Dto dto)
        {
            var iq = _dictionary_IOC._sys_Dictionary_EFCore.QueryAll(d => d.DId == dto.id).Single();
            iq.DName = dto.name;
            iq.DExplain = dto.explain;
            iq.DDiscount=dto.discount;
            _dictionary_IOC._sys_Dictionary_EFCore.Update(iq);
            var result = await _dictionary_IOC._sys_Dictionary_EFCore.SaveChangesAsync();
            return Result(result);
        }
        /// <summary>
        /// 新增会员
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Add_vip(Vip_Request_Dto dto)
        {
            Customervip customerVip = new Customervip()
            {
                CvId = Config.GUID_2(),
                CvAddress = dto.address,
                CvCareer = dto.career,
                CvName = dto.name,
                CvPhone = dto.phone,
                CvQq = dto.qq,
                CvWechat = dto.wechat,
                CvResponsible = dto.responsible,
                CvCustomerId = dto.customer_id,
                CvCreateTime = DateTime.Now,
                CvConsumptionAmount = 0,
                CvConsumptionGiftAmount = 0,
                CvGiftAmount = 0,
                CvRechargeAmount = dto.rechargeAmount,
                CvDesc = null,
                CvLastTime = null,
                CvTransactionCount = 0,
                CvLevel=dto.lv,
                CvCreationTime = DateTime.Now,
                
            };
            _customer_IOC._customer_vip_EFCore.Add(customerVip);

            var result = _customer_IOC._customer_vip_EFCore.SaveChanges();
            return Result(result);
        }
        /// <summary>
        /// 删除会员
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Del_vip(string id)
        {
            var iq = _customer_IOC._customer_vip_EFCore.QueryAll(d => id.Contains(d.CvId));
            _customer_IOC._customer_vip_EFCore.DeleteRange(iq);
            var result = await _customer_IOC._customer_vip_EFCore.SaveChangesAsync();
            return Result(result);
        }
        public async Task<Api_Response_Dto> Recharge_vip(string id, decimal money,string? desc)
        {
            var iq = _customer_IOC._customer_vip_EFCore.QueryAll(d => id==d.CvId).Single();
            var moeny2 = iq.CvRechargeAmount + money;
            iq.CvRechargeAmount= moeny2;
            iq.CvBalance += money;
            _customer_IOC._customer_vip_EFCore.Update(iq);
             _customer_IOC._customer_vip_EFCore.SaveChanges();

            Recharge recharge = new Recharge()
            {
                RId = Config.GUID_2(),
                RCvipId=iq.CvId,
                RDateTime=DateTime.Now,
                RMoney=money,
                RDesc=desc,
            };
            _customer_IOC._recharge_EFCore.Add(recharge);

            var result=await _customer_IOC._recharge_EFCore.SaveChangesAsync();
            return Result(result);
        }
        
    }
}
